package drds.global_transaction.resource_manager.proxy.resource_manager;

import drds.global_transaction.resource_manager.ParameterObjectList;
import drds.global_transaction.resource_manager.execute.ExecuteTemplate;
import drds.global_transaction.resource_manager.execute.StatementExecuteTemplate;
import drds.global_transaction.resource_manager.proxy.datasource.AbstractConnectionProxy;
import drds.global_transaction.resource_manager.proxy.datasource.AbstractPreparedStatementProxy;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class PreparedStatementProxy extends AbstractPreparedStatementProxy implements PreparedStatement, ParameterObjectList
{

	public PreparedStatementProxy(AbstractConnectionProxy connectionProxy, PreparedStatement preparedStatement, String sql) throws SQLException
	{
		super(connectionProxy, preparedStatement, sql);
		init();
	}

	@Override
	public boolean execute() throws SQLException
	{
		return ExecuteTemplate.execute(this, new StatementExecuteTemplate<Boolean, PreparedStatement>()
		{
			@Override
			public Boolean execute(PreparedStatement statement, Object... args) throws SQLException
			{
				return statement.execute();
			}
		});
	}

	@Override
	public ResultSet executeQuery() throws SQLException
	{
		return ExecuteTemplate.execute(this, new StatementExecuteTemplate<ResultSet, PreparedStatement>()
		{
			@Override
			public ResultSet execute(PreparedStatement statement, Object... args) throws SQLException
			{
				return statement.executeQuery();
			}
		});
	}

	@Override
	public int executeUpdate() throws SQLException
	{
		return ExecuteTemplate.execute(this, new StatementExecuteTemplate<Integer, PreparedStatement>()
		{
			@Override
			public Integer execute(PreparedStatement statement, Object... args) throws SQLException
			{
				return statement.executeUpdate();
			}
		});
	}

	@Override
	public List<Object>[] getParameterObjectList()
	{
		return objectList;
	}

	@SuppressWarnings("unchecked")
	private void init() throws SQLException
	{
		int parameterCount = statement.getParameterMetaData().getParameterCount();
		this.objectList = new ArrayList[parameterCount];
		for (int i = 0; i < parameterCount; i++)
		{
			objectList[i] = new ArrayList<Object>();
		}
	}

}
